import simplejson as json
from helloweb import htmls

class AppContext:
    pass

class RenderContext:
    def __getattr__(self, name):
        return ''
    
    
class ReqContext:
    def dispatch(self):
        module = self.module
        action = self.action
        args   = self.args
        
        try:
            method = getattr(module, action)
        except:        
            args.append(action)
            method = getattr(module, '__def__')
        method(self, *args)
        self.output.append('')
        
    def json(self, str):
        self.output.append(json.dumps(str))
        
    def out(self, str):
        self.output.append(str)
     
    def render(self, file):
        filename = 'module/%s/template/%s'%(self.modulename, file)
        self._render(filename)
            
    def _render(self, filename):
        args = {'d':self.d,
                'lib':self.lib,
                'ctr':self.module,
                'app':self.app,
                'req':self,
                'cookie': self.cookie,
                'session':self.session,
                'html':htmls}
        template =  self.app_context.template_engine.get_template(filename)
        self.output.append(template.render(**args))
    
    def return_to(self):
        self.redirect_to(self.ref_site())

    def redirect_to(self, url):
        self.status = '302 Moved Temporarily'
        self.header('Location', url)
    
    def dispatch_to(self, modulename, action):
        self.modulename = modulename
        wsgiapp = self.wsgiapp
        if wsgiapp.modules.has_key(modulename):
            module = wsgiapp.modules[modulename]
            reload(module)
            self.module = module
        else:
            module = __import__("module.%s.controller"%modulename, globals(), locals(), ['%s.controller'%modulename])
            wsgiapp.modules[modulename] = module            
            self.module = module 
        self.dispatch()
        
    def header(self, k, v):
        headers = self.headers
        headers.append((k, v))
        
    def ref_site(self):
        environ = self.environ
        
        return environ.has_key('HTTP_REFERER') and environ['HTTP_REFERER'] or ''
    
class Params(dict):
    pass